package org.example.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.httpclient.HttpClient;
import org.checkerframework.checker.units.qual.A;
import org.example.ymcc.domain.Login;
import org.example.ymcc.dto.LoginDto;
import org.example.ymcc.exception.GlobalException;
import org.example.ymcc.mapper.LoginMapper;
import org.example.ymcc.result.JsonResult;
import org.example.ymcc.service.ILoginService;
import org.example.ymcc.util.AssertUtil;
import org.example.ymcc.util.HttpUtil;
import org.example.ymcc.util.jwt.JwtUtils;
import org.example.ymcc.util.jwt.PayloadData;
import org.example.ymcc.util.jwt.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author zcj
 * @since 2024-06-06
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public boolean save(Login entity) {
        int i= 1/0;
        return super.save(entity);
    }

    String url = "http://localhost:10040/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&redirect_uri=%s&password=%s";

    @Override
    public JsonResult login(LoginDto loginDto) {
        Login login = super.getOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, loginDto.getUsername()));
        if(login == null){
            throw new GlobalException("用户名或密码错误");
        }
        String redirect_uri = loginMapper.selectRedirectByClientId(login.getClientId());
        String post_url = String.format(url, login.getClientId(), login.getClientSecret(), login.getUsername(),
                redirect_uri, loginDto.getPassword());
        String JsonData = HttpUtil.sendPost(post_url, null);
        JSONObject jsonObject = JSONObject.parseObject(JsonData);
        login.setPassword(null);
        jsonObject.put("user",login);
        //现在怎么做
        return JsonResult.success().setData(jsonObject);
    }


    /**
     * 专门处理登录成功的业务
     * @param login
     * @return
     */
    private Map<String, String> loginSuccess(Login login) {
        Map<String, String> map = new HashMap<>();
        try {
            //1.用户类型为0的时候（后台管理系统用户），连表查询当前登录用户拥有的权限和菜单  [今天先不做]
            //2.JWT工具类生成JWT字符串  私钥加密  公钥解密
            PrivateKey privateKey = RsaUtils
                    .getPrivateKey(FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream("hrm_auth_rsa")));
            //加密得到token
            PayloadData payloadData = new PayloadData();
            login.setPassword(null);    //置空密码，更安全
            payloadData.setLogin(login);
            String token = JwtUtils.generateTokenExpireInMinutes(payloadData, privateKey, 60*24*30);  //30天过期

            //3.封装到HashMap
            map.put("token", token);
            map.put("currentUser", JSON.toJSONString(login));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = cryptPasswordEncoder.encode("123456");//加密
        String encode1 = cryptPasswordEncoder.encode("123456");//加密
        System.out.println(encode);//
        System.out.println(encode1);
        boolean matches = cryptPasswordEncoder.matches("1213456", encode);//比较
        System.out.println(matches);
    }
}
